// pages/addDogCard/addDogCard.js
const app = getApp();
//const user = JSON.parse(wx.getStorageSync("user"));
const base_url = app.globalData.base_url;
const util = require('../../utils/util.js');

const date = new Date()
const years = []
const months = []
const days = []

for (let i = 1990; i <= date.getFullYear(); i++) {
  years.push(i)
}

for (let i = 1; i <= 12; i++) {
  months.push(i)
}

for (let i = 1; i <= 31; i++) {
  days.push(i)
}


Page({

  /**
   * 页面的初始数据
   */
  data: {
    info:{},
    sex : '-1',
    isPro : '-1',
    pickerFlag: false,
    isdialog: false,
    isconfirm:false,
    years: years,
    birth:'',
    year: date.getFullYear(),
    months: months,
    month: 2,
    days: days,
    day: 2,
    value: [9999, 1, 1],
    formData:{},
    region: ['浙江省', '杭州市', '上城区'],
    customItem: '',
    imgPath:'',
    dog_id:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      dog_id:options.id
    })
    if(this.data.dog_id){
      this.init()
      wx.setNavigationBarTitle({ title: '编辑狗牌' })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

 
  onShareAppMessage: function () {
  
  },
  init(){
    wx.showLoading({
      title: '加载中',
      success:()=>{
        wx.request({
          url: base_url + '/Dog/detail',
          data: {
            'user_token': JSON.parse(wx.getStorageSync("user")).user_token,
            'dog_id': this.data.dog_id
          },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: res => {
            if (res.data.success == '1' && res.data.data) {
              wx.hideLoading();
              this.setData({
                formData:res.data.data,
                region: [res.data.data.province, res.data.data.city, res.data.data.district],
                year:res.data.data.dog_brithday.split[0],
                month:res.data.data.dog_brithday.split[1],
                day:res.data.data.dog_brithday.split[2],
                imgPath: res.data.data.dog_face
              })
              this.setData({
                'formData.dog_face': this.data.formData.dog_face.replace(/https:\/\/m.frenchiesplus.com/g, '')
              })
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 2000
              })
            }
          }
        })
      }
    })
  },
  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value
    })
  },
  selSex:function (e){
    this.setData({'formData.dog_sex':e.currentTarget.dataset.sex})
  },
  selPro:function (e){
    this.setData({'formData.is_ster':e.currentTarget.dataset.pro})
  },
  selBirth:function(){//打开时间选择器
    this.setData({ pickerFlag: !this.data.pickerFlag })
  },
  addimg(){
    wx.chooseImage({
      count: 1,
      success: res => {
        wx.showLoading({
          title: '正在上传',
          success:()=>{
            this.setData({
              imgPath: res.tempFilePaths[0]
            })
            wx.uploadFile({
              url: base_url + '/File/uploadImage',
              name: 'uploads',
              filePath: this.data.imgPath,
              header: {
                'content-type': 'multipart/form-data'
              },
              success: data => {
                let resData = JSON.parse(data.data);
                if (resData.success == '1') {
                  wx.showToast({
                    title: '上传成功',
                    icon: 'success',
                    duration: 2000
                  })
                  this.setData({
                    'formData.dog_face':resData.data.path
                  })
                }
                wx.hideLoading();
                
              }
            })
          }
        })
        this.setData({
          imgPath: res.tempFilePaths[0]
        })
      }
    })    
  },
  saveBirth:function(){//提交生日
    if (!this.data.years || !this.data.month || !this.data.day){
      this.setData({
        pickerFlag: false
      })
      return false;
    }
    this.setData({
      'formData.dog_brithday': util.zero(this.data.year) + '-' + util.zero(this.data.month) + '-' + util.zero(this.data.day),
      pickerFlag:false
    })
  },
  clear:function(){//关闭选择器
    this.setData({ pickerFlag: false})
  },
  bindChange: function (e) {//时间选择器
    const val = e.detail.value
    this.setData({
      year: this.data.years[val[0]],
      month: this.data.months[val[1]],
      day: this.data.days[val[2]]
    })
  },
  getData(e){
    let vtype = e.currentTarget.dataset.vtype;
    let label = 'formData.'+vtype;
    this.setData({
      [label]:e.detail.value
    })
    
  },
  confirm:function(){
    if (!this.data.formData.dog_face){
      wx.showToast({
        title: '请上传头像',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    wx.showModal({
      title: '提示',
      content: '确认提交狗牌？',
      success:  res => {
        if (res.confirm) {//提交狗牌
          let data = this.data.formData;
          data.photo_list=[]
          if(!data.dog_name){
            wx.showToast({
              title: '请输入名字',
              icon: 'none',
              duration: 2000
            })
          } else if (!data.dog_birthday){
            wx.showToast({
              title: '请输入生日',
              icon: 'none',
              duration: 2000
            })
          } else if (!data.describe){
            wx.showToast({
              title: '请输入描述',
              icon: 'none',
              duration: 2000
            })
          }
          data.user_token = JSON.parse(wx.getStorageSync("user")).user_token;
          data.province = this.data.region[0];
          data.city = this.data.region[1];
          data.district = this.data.region[2];
          
          wx.showLoading({
            title: '正在生成狗牌',
            success:()=>{
              wx.request({
                url: base_url + '/Dog/addOrEdit',
                data: data,
                method: 'POST',
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                success: res => {
                  if (res.data.success == '1') {
                    console.log(res)
                    wx.hideLoading();
                    this.setData({
                      dog_id: res.data.data.card_number,
                      isdialog: true,
                      isconfirm: true
                    })
                  }else{
                    wx.showToast({
                      title: res.data.msg,
                      icon: 'none',
                      duration: 2000
                    })
                  }
                }
              })
            }
          })
          
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

 
  },
  close:function(){
    this.setData({
      isdialog: false
    })
    wx.redirectTo({
      url: '../dogCard/dogCard',
    })
  }
})